package com.bwie.service.impl;

import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.Menu;
import com.bwie.common.domain.UserRole;
import com.bwie.common.utils.JwtUtils;
import com.bwie.mapper.MenuMapper;
import com.bwie.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @className: MenuServiceImpl
 * @Description: TODO
 * @version: v1.８.0
 * @author: 房新路
 * @date: 2025/8/4 17:52
 */
@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private HttpServletRequest request;
    @Override
    public List<Menu> menuList() {
        String token = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        UserRole  userRole = (UserRole) redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY+userKey);
        Integer roleId = userRole.getRoleId();
        List<Menu> menuList=menuMapper.menuList(roleId);
        List<Menu> menus=MenuTree(menuList,0);
        return menus;
    }

    private List<Menu> MenuTree(List<Menu> menuList, Integer pid) {
        ArrayList<Menu> menuArrayList = new ArrayList<>();
        for (Menu menu : menuList) {
            if(menu.getPid()==pid){
                List<Menu> list=MenuTree(menuList,menu.getId());
                menu.setChickedList(list);
                menuArrayList.add(menu);
            }
        }
        return menuArrayList;
    }
}